package com.lq.javawebTest.core;

import com.lq.javawebTest.core.inter.Servlet;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//Servlet的容器
public class ServletContainer{

    //维护一个Hashmap
    private static final Map<String, Servlet> SERVLETS = new ConcurrentHashMap<>(8);

    public static void setServlets(String key, Servlet servlet){
        SERVLETS.put(key, servlet);
    }

    //实现一个懒加载
    public Servlet get(String key){
        //获取的时候看看容器中是否已经有了对应的serlvet
        Servlet servlet = SERVLETS.get(key);
        if(servlet == null){
            //使用配置类Configuration加载这个servlet的权限定名称
            Map<String, String> servlets = Configuration.getSERVLETS();
            String className = servlets.get(key);
            try {
                servlet = (Servlet) Class.forName(className).newInstance();
                SERVLETS.put(key, servlet);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

        }
        return SERVLETS.get(key);
    }
}
